import React, { useRef, useState } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import { PlusOutlined, EllipsisOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Tag, Space, Menu, Dropdown, Avatar, Switch, Modal, message } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { getUsers, switchBtn, addUsers, updateUsers } from '@/services/swagger/user'
import ProForm, { ProFormText } from '@ant-design/pro-form';

const UserManager = () => {
  const actionRef = useRef();
  const [form] = ProForm.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(true);
  const [userid, setUserId] = useState(undefined);

  const columns = [
    {
      title: "头像",
      dataIndex: "avatar_url",
      hideInSearch: true,
      render: (_, record) => (
        <Avatar size={32} icon={<UserOutlined />} src={record.avatar_url} />
      )
    },
    {
      title: "姓名",
      dataIndex: "name",
    },
    {
      title: "邮箱",
      dataIndex: "email",
    },
    {
      title: "是否禁用",
      dataIndex: "is_locked",
      hideInSearch: true,
      render: (_, record) => (
        <Switch
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.is_locked === 0}
          onChange={() => switchBtn(record.id)}
        />
      )
    },
    {
      title: "创建时间",
      dataIndex: "created_at",
      hideInSearch: true,
    },
    {
      title: "操作",
      hideInSearch: true,
      render: (_, record) => (
        <a onClick={() => openEdit(record)}>编辑</a>
      )
    },
  ]

  const getData = async (params: any) => {
    const response = await getUsers(params);
    return {
      data: response.data,
      success: true,
      total: response.meta.pagination.total,
    }
  }

  const isShowModal = (flag: boolean) => {
    setIsModalVisible(flag);
  };

  const handleSubmit = async (values: object) => {
    // console.log('values: ', values);
    if (isEdit) {
      await addUsers(values);
      message.success("添加成功");
    } else {
      values.id = userid;
      await updateUsers(values);
      message.success("修改成功");
    }
    actionRef.current.reload();
    isShowModal(false);
  }

  const openEdit = (obj) => {
    form.setFieldsValue(obj);
    setIsEdit(false);
    setUserId(obj.id);
    isShowModal(true);
  }

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}) => getData(params)}
        /* editable={{
          type: 'multiple',
        }} */
        /* columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }} */
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="用户列表"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => { setIsEdit(true); isShowModal(true) }}
          >
            新建
          </Button>,
          /* <Dropdown key="menu" overlay={menu}>
          <Button>
            <EllipsisOutlined />
          </Button>
          </Dropdown>, */
        ]}
      />

      <Modal
        destroyOnClose
        title={isEdit ? "添加用户" : "编辑用户"}
        visible={isModalVisible}
        // onOk={handleOk}
        onCancel={() => isShowModal(false)}
        footer={false}
      >
        <ProForm
          className="form-content"
          onFinish={(values) => handleSubmit(values)}
          form={form}
          preserve={false}
          submitter={{
            // 配置按钮文本
            searchConfig: {
              submitText: isEdit ? '新增' : '修改',
            },
          }}
        >
          <ProFormText
            name="name"
            required
            label="用户名"
            placeholder="请输入用户名"
            rules={[{ required: true, message: '用户名必填项' }]}
          />
          <ProFormText
            name="email"
            required
            label="邮箱"
            placeholder="请输入邮箱"
            fieldProps={{ autoComplete: 'new-password' }}
            rules={[
              { required: true, message: '邮箱必填项' },
              { type: "email", message: '邮箱格式不正确' },
            ]}
          />
          {
            isEdit ? <ProFormText.Password
              name="password"
              required
              label="密码"
              placeholder="请输入密码"
              fieldProps={{ autoComplete: 'new-password' }}
              rules={[
                { required: true, message: '密码必填项' },
                { min: 6, message: '密码至少6位' },
              ]}
            /> : ''
          }
        </ProForm>
      </Modal>
    </PageContainer>
  )
}

export default UserManager